package com.study.example.commonUnsafe;

import com.study.example.count.CountExample1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-07-15 19:55
 * @description
 */
public class StringExample1 {

    private static final Logger logger = LoggerFactory.getLogger(CountExample1.class);

    /**
     * 请求总数
     */
    public static int clientTotal = 5000;

    /**
     * 同时并发执行的线程数
     */
    public static int threadTotal = 200;

    private static StringBuilder stringBuilder = new StringBuilder();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    // 当前这个线程是否允许被执行 如果acquire不能返回值则add()的方法不被执行 返回则可以
                    semaphore.acquire();
                    append();
                    // 释放当前的进程
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 每执行返一次clientTotal的值就会减一个
                countDownLatch.countDown();
            });
        }
        try {
            // 当所有请求执行完毕才可以走下面的方法 及clientTotal减为0
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 关闭线程池
        executorService.shutdown();
        logger.info("size:{}", stringBuilder.length());
    }

    private static void append() {
        stringBuilder.append("1");
    }
}
